package com.homelink.crashhandle.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import com.callrecorder.asynchttp.AsyncHttpUtil;
import com.callrecorder.asynchttp.callable.UploadRequestCallable;
import com.homelink.crashhandle.util.ConstantsUtils;
import com.homelink.crashhandle.util.FileUtils;
import com.homelink.crashhandle.util.LogUtils;
import org.apache.http.Header;
import org.apache.http.cookie.Cookie;

import java.io.File;
import java.util.List;

/**
 * Created by Fcy on 2015/12/29. 封装一个UpLoadManager
 */
public class UploadFileService extends Service implements UploadRequestCallable
{
	private static final String TAG = UploadFileService.class.getSimpleName();
	private boolean is_crash;
	// 本app用到的断点续传定义：将文件以最小单位进行分段，发送每一段，收到ack后发送下一个分段。
	private int fileTotalNum = 0;
	private int mPos = -1;
	private List<File> mFileList;
	private String mFileName;

	public IBinder onBind(Intent intent)
	{
		return null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId)
	{
		LogUtils.e(TAG, "UploadFileService onStartCommand");
		if (intent != null)
		{
			is_crash = intent.getBooleanExtra(ConstantsUtils.IS_CRASH, false);

			// 1. get upload file list
			mFileList = FileUtils.getPushFiles();
			if (mFileList != null && mFileList.size() > 0)
			{
				fileTotalNum = mFileList.size();
				mPos = 0;
				uploadFile(mFileList.get(mPos));

				LogUtils.e(TAG, "push = " + is_crash + ",file count = "
				        + mFileList.size());
			}
			else
			{
				LogUtils.e(TAG, "file num is empty!");
			}
		}

		// return START_NOT_STICKY;
		return super.onStartCommand(intent, flags, startId);
	}

	private void uploadFile(File file)
	{
		// 获取file的name
		mFileName = file.getName();
		Log.d(TAG, "uploadFile Name : " + mFileName);
		AsyncHttpUtil.upload(ConstantsUtils.UPLOAD_FILE_URL, null, mFileName,
		        file, this);
	}

	public void onSuccess(String responseInfo)
	{
		LogUtils.e(TAG, "upload onSuccess:responseInfo=" + responseInfo);

		// 删除本地文件，fixme 有可能删除失败？
		boolean isDel = FileUtils.deleteFile(mFileList.remove(mPos));
		// mFileList.remove(mPos);
		--fileTotalNum;

		if (fileTotalNum > 0)
		{
			uploadFile(mFileList.get(mPos));
		}
		else
		{
			LogUtils.e(TAG, "file has been completely uploaded~");
			// 服务停止
			stopSelf();
		}

	}

	public void onStart()
	{
		LogUtils.e(TAG, "upload onStart");
	}

	public void onFinish()
	{
		LogUtils.e(TAG, "upload onFinish");
	}

	public void onCancel()
	{
		LogUtils.e(TAG, "upload onFinish");
	}

	public void onSuccess(Header[] headers, List<Cookie> cookies)
	{
		LogUtils.e(TAG, "upload onSuccess");
	}

	/**
	 * 失败回调
	 * 
	 * @param errorCode
	 * @param errorMsg
	 */
	public void onFailed(int errorCode, String errorMsg)
	{
		LogUtils.e(TAG, "upload onFailed: errorCode=" + errorCode + "errorMsg="
		        + errorMsg);
		// stopSelf();
	}

	public void onStartTransfer()
	{

	}

	public void onTransfering(String name, long totalLength,
	        long transferedLength)
	{

	}

	public void onTransferSuc(String name)
	{

	}
}
